package yams.domain;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
import yams.utils.SystemTool;

import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * 资产模型维护
 * Created by Silence on 2016/11/3.
 */
@Entity
@Table(name = "T_CATEGORY", schema = AbstractEntity.DB_SCHEMA)
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@JsonIgnoreProperties({"parent", "children", "cateAttrs", "products"})
public class CategoryEntity extends AbstractEntity {

    String icon;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
    @JoinColumn(name = "PARENT_ID")
    CategoryEntity parent;

    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
    @OrderBy(value = "rowNum DESC")
    Set<CategoryEntity> children;

    @OneToMany(mappedBy = "category", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
    @OrderBy(value = "rowNum ASC")
    Set<CateAttrEntity> cateAttrs;

    @OneToMany(mappedBy = "category", cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
    @OrderBy(value = "rowNum DESC")
    Set<ProductEntity> products;

    public String getType() {
        String type;
        if (this.getChildren() != null && this.getChildren().size() > 0)
            type = "folder";
        else
            type = "leaf";
        return type;
    }

    public void saveAttr(Set<CateAttrEntity> set,String user) {
        if (this.getCateAttrs() != null)
            this.getCateAttrs().clear();
        if(set != null && set.size()>0){
            if(this.cateAttrs==null)
                this.cateAttrs = new HashSet<>();
//            IAttributeRepository attributeRepository = ContextUtil.getBean("attributeRepository",IAttributeRepository.class);
            set.forEach(a->{
                a.setId(SystemTool.uuid());
                a.setCreatedDate(new Date());
                a.setModifiedDate(new Date());
                a.setCreateBy(user);
                a.setModifiedBy(user);
                a.setCode(this.getCode()+"-"+a.getAttrId());
                a.setName(a.getCode());
                a.setCategory(this);
                this.cateAttrs.add(a);
            });
        }
    }
}
